package net.sxnic.normal.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityNotFoundException;

import net.sxnic.comm.CommConstant;
import net.sxnic.item.ItemConstants;
import net.sxnic.item.catalog.Catalog;
import net.sxnic.item.catalog.CatalogManager;
import net.sxnic.item.clpv.Clpv;
import net.sxnic.item.clpv.ClpvManager;
import net.sxnic.item.duiying.Duiying;
import net.sxnic.item.duiying.DuiyingManager;
import net.sxnic.item.zzdw.Zzdw;
import net.sxnic.item.zzdw.ZzdwManager;
import net.sxnic.jhitem.itemoperation.ItemOperation;
import net.sxnic.jhitem.itemoperation.ItemOperationManager;
import net.sxnic.ugr.dept.Dept;
import net.sxnic.ugr.dept.DeptManager;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ItemImportUtils {

	private static Logger logger = LoggerFactory
			.getLogger(ItemImportUtils.class);

	public static void importItem(CatalogManager ctManager,
			ClpvManager clpvManager, ZzdwManager zzdwManager,
			DeptManager deptManager,DuiyingManager dyManager, ItemOperationManager operationManager,String filePath) throws IOException {
		File file = new File(filePath);

		if (!file.exists()) {
			logger.error("file : " + filePath + " is null");
			return;
		}

		List<String> lines = FileUtils.readLines(file, "utf-8");
		List<String> catalogs_lines = new ArrayList<String>();
		List<String> zzdw_lines = new ArrayList<String>();
		//List<String> gzdw_lines = new ArrayList<String>();
		List<String> duiying_lines = new ArrayList<String>();
		List<String> operation_lines = new ArrayList<String>();

		String suffix = "";

		for (String line : lines) {

			if (StringUtils.isBlank(line)
					|| line.contains(CommConstant.TXT_IGNORE_CHARS)) {
				continue;
			}

			// 类别
			if (line.startsWith("C")) {
				suffix = "C";
				continue;
			} else if (line.startsWith("Z")) {
				// 组织单位
				suffix = "Z";
				continue;
			} else if (line.startsWith("D")) {
				// 对应关系
				suffix = "D";
				continue;
			}else if (line.startsWith("O")) {
				// 对应关系
				suffix = "O";
				continue;
			}

			if ("C".equals(suffix)) {
				catalogs_lines.add(line);
				System.out.println("----"+line);
			} else if ("D".equals(suffix)) {
				duiying_lines.add(line);
			}else if ("Z".equals(suffix)) {
				System.out.println(line);
				zzdw_lines.add(line);
			}else if ("O".equals(suffix)) {
				operation_lines.add(line);
			} 
			
		}		
		importCatalog(ctManager, clpvManager, catalogs_lines);		
		importZzdw(ctManager, zzdwManager, deptManager, zzdw_lines);
		importDuiying(dyManager,duiying_lines);
		importOperation(operationManager,operation_lines);
		//importGzdw(ctManager, zzdwManager, deptManager, gzdw_lines);
	}

	public static void importCatalog(CatalogManager ctManager,
			ClpvManager clpvManager, List<String> lines) throws IOException {

		Catalog parent = null;
		for (String line : lines) {

			if (StringUtils.isBlank(line)
					|| line.contains(CommConstant.TXT_IGNORE_CHARS)) {
				continue;
			}

			String[] m = line.split(",");
			Catalog temp = ctManager.findByUnique("code", m[0]);

			if (temp == null) {
				temp = new Catalog();
				temp.setCode(m[0]);
				temp.setName(m[1]);
				temp.setAlias(m[2]);
			} else {
				temp.setCode(m[0]);
				temp.setName(m[1]);
				temp.setAlias(m[2]);
			}
			
			ctManager.update(temp);

			// 父子关系
			if (StringUtils.isNotBlank(m[3])) {
				parent = ctManager.findByUnique("code", m[3]);
				if (parent != null) {
					temp.setParent(parent);
					ctManager.update(temp);

					if (!parent.getChild().contains(temp)) {
						parent.getChild().add(temp);
						ctManager.update(parent);
					}
				}
			}

			// 自动创建类别权限表
			clpvManager.deleteByCatalog(temp);

			Clpv c = null;
			for (String suffix : Clpv.DEFAULT_PERMISSIONS) {
				c = new Clpv();
				if (temp.getParent() == null) {
					// 大类别
					c.setPvName(temp.getAlias() + suffix);
				} else {
					// 小类别
					c.setPvName(temp.getParent().getAlias() + "."
							+ temp.getCode() + suffix);
				}

				clpvManager.save(c);
			}
		}
	}

	/**
	 * 导入组织单位
	 * @description gcjszx_gldw:001
		gcjszx_zzdw:002,003,004,005,006,007,008,009,010,011,012
		gcjszx_gzdw:g023001,023002
		分别对应大类为jcjszx 的 管理单位、组织单位、工作单位
	 * @param ctManager
	 * @param zzdwManager
	 * @param deptManager
	 * @param lines
	 */
	public static void importZzdw(CatalogManager ctManager,
			ZzdwManager zzdwManager, DeptManager deptManager, List<String> lines) {
		
		zzdwManager.clear();
		
		for (String line : lines) {

			if (StringUtils.isBlank(line)
					|| line.contains(CommConstant.TXT_IGNORE_CHARS)) {
				continue;
			}

			String before = StringUtils.substringBefore(line, ":");
			String after = StringUtils.substringAfter(line, ":");
			String catalogAlias = StringUtils.substringBefore(before, "_");
			String zzdwCate = StringUtils.substringAfter(before, "_");

			String[] m = after.split(",");
			Catalog c = ctManager.findByUnique("alias", catalogAlias);

			if (c == null) {
				throw new EntityNotFoundException("===catalog:" + catalogAlias
						+ "===is null===");
			}

			Zzdw z = null;
			Dept d = null;
			
			for (String z_m : m) {
				z = zzdwManager.findByUnique("deptCode", z_m);
				d = deptManager.findByCode(z_m);
				if (d == null) {
					throw new EntityNotFoundException("===DeptCode:" + z_m
							+ "==Dept==is null===");
				}

				if (z == null) {
					z = new Zzdw();
					z.setCatalogCode(c.getCode());
					z.setCatalogAlias(catalogAlias);
					z.setDeptCode(d.getCode());
					z.setDeptName(d.getName());
					z.setCate(zzdwCate);
					z.setXorder(d.getDeptOrder());
				} else {
					z.setCatalogCode(c.getCode());
					z.setCatalogAlias(catalogAlias);
					z.setDeptCode(d.getCode());
					z.setDeptName(d.getName());
					z.setCate(zzdwCate);
					z.setXorder(d.getDeptOrder());
				}

				if (StringUtils.isBlank(z.getCatalogCode())) {
					z.setCatalogCode(c.getCode());
					z.setCatalogAlias(c.getAlias());
				} else if (!StringUtils.contains(z.getCatalogCode(),
						c.getCode())) {
					z.setCatalogCode(z.getCatalogCode() + "," + c.getCode());
					z.setCatalogAlias(z.getCatalogCode() + "," + c.getAlias());
				}
				
				//工作单位需要配对组织单位
				if(Zzdw.GZDW_CATE.equals(zzdwCate)){
					z.setParentDetpCode(StringUtils.left(z.getDeptCode(), z.getDeptCode().length()-3));
				}

				zzdwManager.save(z);
				logger.debug("===大类:{}===组织单位:{}===保存成功===", before,
						d.getName());
			}
		}
	}

	public static void importGzdw(CatalogManager ctManager,
			ZzdwManager zzdwManager, DeptManager deptManager, List<String> lines) {
		for (String line : lines) {

			if (StringUtils.isBlank(line)
					|| line.contains(CommConstant.TXT_IGNORE_CHARS)) {
				continue;
			}

			String before = StringUtils.substringBefore(line, ":");
			String after = StringUtils.substringAfter(line, ":");

			String[] m = after.split(",");
			Catalog c = ctManager.findByUnique("alias", before);

			if (c == null) {
				throw new EntityNotFoundException("===catalog:" + before
						+ "===is null===");
			}

			Zzdw z = null;
			Dept d = null;
			for (String z_m : m) {
				z = zzdwManager.findByUnique("deptCode", z_m);
				d = deptManager.findByCode(z_m);
				if (d == null) {
					throw new EntityNotFoundException("===DeptCode:" + z_m
							+ "==Dept==is null===");
				}

				if (z == null) {
					z = new Zzdw();
					z.setCatalogCode(c.getCode());
					z.setCatalogAlias(c.getAlias());
					z.setDeptCode(d.getCode());
					z.setDeptName(d.getName());
				} else {
					z.setCatalogCode(c.getCode());
					z.setCatalogAlias(c.getAlias());
					z.setDeptCode(d.getCode());
					z.setDeptName(d.getName());
				}

				z.setCate(Zzdw.GZDW_CATE);
				z.setParentDetpCode(StringUtils.left(z_m, z_m.length() - 3));

				if (StringUtils.isBlank(z.getCatalogCode())) {
					z.setCatalogCode(c.getCode());
					z.setCatalogAlias(c.getAlias());
				} else if (!StringUtils.contains(z.getCatalogCode(),
						c.getCode())) {
					z.setCatalogCode(z.getCatalogCode() + "," + c.getCode());
					z.setCatalogAlias(z.getCatalogCode() + "," + c.getAlias());
				}

				zzdwManager.save(z);
				logger.debug("===大类:{}===工作单位:{}===保存成功===", before,
						d.getName());
			}
		}
	}

	public static void importDuiying(DuiyingManager dyManager,
			List<String> lines) {
		
		//clear table
		dyManager.clear();
		//2014,gxcgcjs, ,2014,
		
		for (String line : lines) {

			if (StringUtils.isBlank(line)
					|| line.contains(CommConstant.TXT_IGNORE_CHARS)) {
				continue;
			}
			
			String[] m = StringUtils.split(line, ",");
			Duiying dy=new Duiying();			
			
			dy.setCyear(m[0]);
			dy.setCate1(m[1]);
			dy.setCate2(m[2]);
			dy.setDyYear(m[3]);
			
			dyManager.save(dy);

			logger.debug("=======catalog与年份对应保存成功====");
		}
	}
		
		public static void importOperation(ItemOperationManager operationManager,
				List<String> lines) {
			
			//clear table
			operationManager.clear();
			
			for (String line : lines) {

				if (StringUtils.isBlank(line)
						|| line.contains(CommConstant.TXT_IGNORE_CHARS)) {
					continue;
				}
				
				String[] m = StringUtils.split(line, ",");
				ItemOperation itemOperation=new ItemOperation();			
				
				itemOperation.setCatalog1(ItemConstants.SYSTEM_CALALOG_ALIAS);
				itemOperation.setCatalog2("001");
				itemOperation.setSoperCode(m[0].trim());
				itemOperation.setSoperName(m[1].trim());
				itemOperation.setSoperShortname(m[2].trim());
				itemOperation.setDepartment(m[3].trim());
				itemOperation.setPagePath(m[4].trim());
				
				operationManager.save(itemOperation);

				logger.debug("=======itemOperation项目类别保存成功====");
			}
	}
}
